package com.test.designpattern.proxy.dynamic.jdk.handler;

import com.test.designpattern.proxy.dynamic.jdk.extend.DbTransaction;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * handler，作为代理类，执行目标方法、以及增强的方法
 */
public class UserHandler1 implements InvocationHandler {

    // 目标类实例
    private Object object;

    // 增强类
    private DbTransaction dbTransaction;

    public UserHandler1(Object object, DbTransaction dbTransaction) {
        this.object = object;
        this.dbTransaction = dbTransaction;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Object res = null;

        if (method.getName().equals("insert")) {
            //前置增强
            dbTransaction.beginTransaction();

            //目标方法
            res = method.invoke(object, args);

            //后置增强
            dbTransaction.endTransaction();
        } else {
            method.invoke(object, args);
        }

        return res;
    }
}
